package com.amanda.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.amanda.constant.RedisConstant;
import com.amanda.entity.PageResult;
import com.amanda.entity.QueryPageBean;
import com.amanda.entity.Result;
import com.amanda.pojo.Setmeal;
import com.amanda.service.SetMealService;
import com.amanda.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.amanda.constant.MessageConstant;
import redis.clients.jedis.JedisPool;
import java.io.IOException;
import java.util.UUID;


/**
 * @author amanda
 * @Description 套餐管理
 */

@RestController
@RequestMapping("/setmeal")
public class SetMealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetMealService setMealService;

    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        // 获取原始文件名，截取后缀
        String originalFilename = imgFile.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index - 1);
        String fileName = UUID.randomUUID().toString() + substring;

        try {
            // 上传到七牛云服务器
            QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);
            // 存储到redis
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setMealService.add(setmeal, checkgroupIds);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);
        }
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        return setMealService.findPage(queryPageBean);
    }
}
